import { Command, Option } from 'clipanion'

import { runCypress } from '../webpack/run-cypress'

import { generateCi } from './e2e-ci-generator'
import { spawn } from './spawn'

export class E2ECommand extends Command {
  static paths = [[`e2e`]]

  isGenCiJobs: boolean = Option.Boolean('-g,--genCi')!

  shouldOpen: boolean = Option.Boolean(`-o,--open`)!

  parallel: boolean = Option.Boolean(`-p,--parallel`)!

  taskId: string = Option.String(`-t,--taskId`)!

  async execute() {
    if (this.isGenCiJobs) {
      generateCi()
      return
    }
    await this.preBuild()
    await runCypress({ open: Boolean(this.shouldOpen), parallel: Boolean(this.parallel), taskId: this.taskId })
  }

  private async preBuild() {
    // dist folder is @slardar/integrations's final product.build it before run e2e
    await spawn(
      'SIMPLE_BUILD=true CYPRESS_BUILD=true NODE_ENV=development yarn cli bundle -ps slardar-lite,integrations,apmplus-integrations',
    )
    // for web loader.spec.ts
    await spawn('NODE_ENV=development yarn nx run @slardar/web:build')
  }
}
